package com.spring.poi.tl.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.AttachmentType;
import com.deepoove.poi.data.Attachments;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.policy.AttachmentRenderPolicy;
import com.deepoove.poi.util.ByteUtils;
import com.deepoove.poi.util.PoitlIOUtils;
import com.spring.poi.tl.config.VideoRenderPolicy;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuzhiqiang
 */
@RestController
@RequestMapping("/")
public class TestController {

    @GetMapping("/test")
    public void test(HttpServletResponse response) throws IOException, OpenXML4JException {

        XWPFDocument doc = new XWPFDocument(new ClassPathResource("word/test.docx").getInputStream());

        XWPFDocument doc2 = new XWPFDocument(new ClassPathResource("word/test2.docx").getInputStream());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=\"" + "out_template.docx" + "\"");

        File file = new ClassPathResource("word/video.docx").getFile();

        Map map = new HashMap(15);
        map.put("title", "Hi, poi-tl Word模板引擎");
        map.put("img", Pictures.ofUrl("http://deepoove.com/images/icecream.png")
                .size(100, 100).create());
        File attachmentFile = new ClassPathResource("word/attachment.docx").getFile();
        map.put("attachment", Attachments.ofBytes(ByteUtils.getLocalByteArray(attachmentFile), AttachmentType.DOCX)
                .create());
        File shipinFile = new ClassPathResource("mp4/test.mp4").getFile();
        map.put("shipin", shipinFile);

        Configure configure = Configure.builder()
                .bind("attachment", new AttachmentRenderPolicy())
                .bind("shipin", new VideoRenderPolicy())
                .build();

        XWPFTemplate template = XWPFTemplate.compile(file, configure).render(map);

        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
    }
}
